package daybook.io.formatter;

import com.github.mustachejava.*;
import com.github.mustachejava.resolver.ClasspathResolver;
import daybook.Resources;
import daybook.exception.ApplicationException;

import java.io.IOException;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.util.Objects;

/**
 * Created by crc on 16-9-2.
 */
public class MustacheTemplateEngine implements TemplateEngine {
    private static final MustacheTemplateEngine INSTANCE = new MustacheTemplateEngine();
    private final MustacheFactory mustacheFactory;

    public static MustacheTemplateEngine getInstance() {
        return INSTANCE;
    }

    public MustacheTemplateEngine(MustacheFactory mustacheFactory) {
        this.mustacheFactory = Objects.requireNonNull(mustacheFactory);
    }

    public MustacheTemplateEngine() {
        this(new DefaultMustacheFactory(new MustacheResolver() {
            private final ClasspathResolver resolver = new ClasspathResolver();
            @Override
            public Reader getReader(String resourceName) {
                return resolver.getReader(Resources.get(resourceName));
            }
        }));
    }

    @Override
    public void write(String template, Object model, Writer writer) {
        final Mustache mustache = mustacheFactory.compile(template);
        try {
            mustache.execute(writer, model).flush();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } catch (MustacheException e) {
            throw new ApplicationException(e);
        }
    }
}
